﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace Dye_Lib
{
    public class BinaryManager<T>
    {   
        
        //private Type tiepe;
        //public Type Tiepe
        //{
        //  get { return tiepe; }
        //  set { tiepe = value; }
        //}     

        //public T Load(string path)
        //{
        //    T instance;
        //    using (TextReader reader = new StreamReader(path))
        //    {
        //        XmlSerializer xml = new XmlSerializer(tiepe);
        //        instance = (T)xml.Deserialize(reader);
        //    }
        //    return instance;
        //}

        //public void Save(string path, object obj)
        //{
        //    using (TextWriter writer = new StreamWriter(path))
        //    {
        //        XmlSerializer xml = new XmlSerializer(tiepe);
        //        xml.Serialize(writer, obj);
        //    }
        //}
        public void Save(string path, object obj)
        {            
            // To serialize the hashtable and its key/value pairs,   
            // you must first open a stream for writing.  
            // In this case, use a file stream.
            //FileStream fs = new FileStream(path, FileMode.Create);

            //// Construct a BinaryFormatter and use it to serialize the data to the stream.
            //BinaryFormatter formatter = new BinaryFormatter();
            //formatter.Serialize(fs, obj);
            //fs.Close();
            using (Stream fileStream = new FileStream(path, FileMode.Create,
                           FileAccess.Write, FileShare.None))
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fileStream, obj);
                fileStream.Close();
            }            
        }


        public T Load(string path)
        {
            T instance;
            //// Open the file containing the data that you want to deserialize.
            //FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
            //BinaryFormatter formatter = new BinaryFormatter();

            //// Deserialize the hashtable from the file and  
            //// assign the reference to the local variable.
            //instance = (T)formatter.Deserialize(fs);
            //fs.Close();
            //return instance;
            using (Stream fileStream = new FileStream(path, FileMode.Open,
                           FileAccess.Read, FileShare.Read))
            {
                IFormatter formatter = new BinaryFormatter();
                instance = (T)formatter.Deserialize(fileStream);
                fileStream.Close();
                return instance;
            }                      
        }
    }
}
